/****************************************************
          File Name:10-8_imply.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Wed 24 Dec 2014 11:32:51 AM CST
*****************************************************/

#include"10-8.h"
using std::nullptr_t;
List::List()
{
    head = nullptr;
    len = 0;
}

bool List::isempty()
{
    return len == 0;
}

bool List::isfull()
{
    return len == max;
}

void List::add()
{
    std::string name;
    Item *cur = new Item;
    Item *pre = head;

    std::cout << "Enter name: ";
    std::getline(std::cin, name);

    if(isempty())
        head = cur;
    else
    {
        while(pre->next != nullptr)     // 'pre != nullptr' is totally wrong!!!!
            pre = pre->next;
        pre->next = cur;
    }

    cur->name = name;
    cur->next = nullptr;
    pre = cur;

    len++;
}

void List::rm(std::string name)
{
    Item *tmp = head;
    Item *pre = nullptr;

    while(tmp != nullptr && tmp->name != name)
    {
        pre = tmp;
        tmp = tmp->next;
    }

    pre->next = tmp->next;     // can NOT delete head pointer !!!

    delete tmp;
}

void List::show() const
{
    Item *tmp = head;
    while(tmp != NULL)
    {
        std::cout << tmp->name << std::endl;
        tmp =  tmp->next;
    }
}

void List::destroy()
{
    while(head != NULL)
    {
        delete head;
        head = head->next;
    }
}
